package com.wawei.seeds;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.igexin.sdk.PushManager;
import com.wawei.seeds.model.ExpertInfo;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.services.WalnutExpertServiceHandler;
import com.wawei.seeds.services.WalnutRegAuthServiceHandler;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit.RestAdapter;

/**
 * Created by itachi on 15/7/16.
 */
public class StartActivity extends Activity {

    @InjectView(R.id.back_image)ImageView backView;
    @InjectView(R.id.mask_image)ImageView backMask;

    private static final int SCHEDULER_THREAD = 1;
    private static final int SPLASH_PERIOD = 3;

    private static int login_count = 0;

    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(SCHEDULER_THREAD);
    private ScheduledFuture future;

    private Bitmap splashImage = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        PushManager.getInstance().initialize(this.getApplicationContext());

        ButterKnife.inject(this);

        splashImage = BitmapFactory.decodeResource(getResources(), R.drawable.start_page_back);

        // 请恕我没看懂下面他妈的是在干屌，按照代码执行图形变换，那图形都日了狗了。
        /*
        float f = dip2px(3.0f); // 3dp转成px
        int width = dip2px(360.0f); // 手机固定的dp宽度转换成对应的px值
        int height = dip2px(640.0f); // 手机固定的dp高度转换成对应的px值
        int bitmapWidth = bitmap.getWidth(); // 获取图片的宽度像素
        int bitmapHeight = bitmap.getHeight(); // 获取图片的高度像素

        float f2 = f * 2.0f; // 6dp的px值
        Bitmap bitmap2 = null;
        // 如果图片的大小小于 6dp * 6dp,则对图片进行缩放,怕不至于有这么小的图片吧？
        if (bitmapWidth < f2 || bitmapHeight < f2) {
            bitmap2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            if (width > height) {
                float f3 = f2 / width;
                Matrix matrix = new Matrix();
                matrix.setScale(f3, f3);
                new Canvas(bitmap2).drawBitmap(bitmap, matrix, new Paint());
            }
        }

        Bitmap bitmap3 = bitmap2 == null ? bitmap : bitmap2;

        Bitmap bitmap4 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap4);
        Rect rect = new Rect(0, 0, width, height);
        RectF rectF = new RectF(rect);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(0xFF424242);
        canvas.drawRoundRect(rectF, f, f, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap3, rect, rect, paint);
        backView.setImageBitmap(bitmap4);
        */

        backView.setImageBitmap(splashImage);

        initTimer();
    }

    private int dip2px(float dpValue) {
        return (int)(0.5f + dpValue * getResources().getDisplayMetrics().density);
    }

    private void initTimer(){
        final Runnable worker = new Runnable() {
            @Override
            public void run() {
                // 把图整回来
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        backMask.setVisibility(View.GONE);
                    }
                });

                if(login_count == 0) {
                    login_count ++;
                    HeroInfo heroInfo = new HeroInfo();
                    String userPassword = PrefUtils.getUserPassword(StartActivity.this);

                    RestAdapter restAdapter = RetrofitNetworkService.makeRestAdapter();
                    WalnutRegAuthServiceHandler serviceHandler = new WalnutRegAuthServiceHandler();
                    WalnutExpertServiceHandler expertServiceHandler = new WalnutExpertServiceHandler(StartActivity.this);

                    if(!userPassword.equals("|||")) {
                        heroInfo.userName = PrefUtils.getPrefUser(StartActivity.this);
                        heroInfo.password = PrefUtils.getPrefPassword(StartActivity.this);


                        try {
                            heroInfo = serviceHandler.login(restAdapter, heroInfo);
                            Thread.sleep(1000);
                        }
                        catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    future.cancel(true);
                    if (heroInfo != null && null != heroInfo.loginToken) {
                        SeedsApp app = (SeedsApp) StartActivity.this.getApplication();
                        app.getSession().put(SeedsApp.LOGIN_USER, heroInfo);
                        PrefUtils.markUserPassword(StartActivity.this, heroInfo.userName, heroInfo.password);
                        PrefUtils.markUserId(StartActivity.this, Integer.valueOf(heroInfo.userId));

                        ExpertInfo expertInfo = expertServiceHandler.checkExpert(restAdapter, heroInfo.userId);
                        if(null != expertInfo){
                            app.getSession().put(SeedsApp.IS_EXPERT, "yes");
                        }
                        else {
                            app.getSession().put(SeedsApp.IS_EXPERT, "no");
                        }
                        Intent mainIntent = new Intent(StartActivity.this, WalnutMainActivity.class);
                        StartActivity.this.startActivity(mainIntent);
                    }
                    else {
                        Intent regIntent = new Intent(StartActivity.this, WalnutLoginActivity.class);
                        StartActivity.this.startActivity(regIntent);
                    }

                    StartActivity.this.finish();
                }
            }
        };

        future = scheduler.scheduleAtFixedRate(worker, 1, 2 * SPLASH_PERIOD, TimeUnit.SECONDS);
    }

    @Override
    protected void onDestroy() {
        scheduler = null;
        login_count = 0;
        splashImage.recycle();
        super.onDestroy();
    }
}
